import store from '@/store/store'
import Setting from '@/setting.env'

export default {
  data() {
    return {
      webSocketUrl: '',
      webSocket: '', // websocket实例对象
      //心跳检测
      heartCheck: {
        vueThis: this, // vue实例
        timeout: 10000, // 超时时间
        timeoutObj: null, // 计时器对象——向后端发送心跳检测
        serverTimeoutObj: null, // 计时器对象——等待后端心跳检测的回复
        // 心跳检测重置
        reset: function () {
          clearTimeout(this.timeoutObj)
          clearTimeout(this.serverTimeoutObj)
          return this
        },
        // 心跳检测启动
        start: function () {
          this.timeoutObj && clearTimeout(this.timeoutObj)
          this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
          this.timeoutObj = setTimeout(() => {
            // 这里向后端发送一个心跳检测，后端收到后，会返回一个心跳回复
            this.vueThis.webSocket.send('HeartBeat')
            console.log('发送心跳检测')
            this.serverTimeoutObj = setTimeout(() => {
              // 如果超过一定时间还没重置计时器，说明websocket与后端断开了
              console.log('未收到心跳检测回复')
              // 关闭WebSocket
              this.vueThis.webSocket.close()
            }, this.timeout)
          }, this.timeout)
        }
      },
      socketReconnectTimer: null, // 计时器对象——重连
      socketReconnectLock: false, // WebSocket重连的锁
      socketLeaveFlag: false // 离开标记（解决 退出登录再登录 时出现的 多次相同推送 问题，出现的本质是多次建立了WebSocket连接）
    }
  },
  computed: {},
  mounted() {
    // websocket启动
    // this.createWebSocket();
  },
  destroyed() {
    // 离开标记
    this.socketLeaveFlag = true
    // 页面关闭销毁
    this.webSocket.close()
    console.log('webSocket关闭关闭')
  },
  methods: {
    // websocket启动
    createWebSocket() {
         let webSocketUrl =
         Setting.WebSocketUrl+
           store.getters.store_userInfo.id +
           '/' +
           store.getters.store_userInfo.entName +
           '/app/' +
           this.rowData.id

      console.log('webSocketUrl', webSocketUrl)
      try {
        if ('WebSocket' in window) {
          this.webSocket = new WebSocket(webSocketUrl)
        } else if ('MozWebSocket' in window) {
          this.webSocket = new MozWebSocket(webSocketUrl)
        }
        // websocket事件绑定
        this.socketEventBind()
      } catch (e) {
        console.log('catch' + e)
        // websocket重连
        this.socketReconnect()
      }
    },
    // websocket事件绑定
    socketEventBind() {
      // 连接成功建立的回调
      this.webSocket.onopen = this.onOpenCallback
      // 连接发生错误的回调
      this.webSocket.onerror = this.onErrorCallback
      // 连接关闭的回调
      this.webSocket.onclose = this.onCloseCallback
      // 向后端发送数据的回调
      this.webSocket.onsend = this.onSendCallback
      // 接收到消息的回调
      this.webSocket.onmessage = this.getMessageCallback

      //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = () => {
        this.webSocket.close()
      }
    },
    // 向后端发送消息
    sendMessage(data) {
      if (this.webSocket != null) {
        this.webSocket.send(JSON.stringify(data))
        console.log('websocket发送消息:', JSON.stringify(data))
      } else {
        this.$Message.error('已断开连接')
      }
    },
    // websocket重连
    socketReconnect() {
      if (this.socketReconnectLock) {
        return
      }
      this.socketReconnectLock = true
      this.socketReconnectTimer && clearTimeout(this.socketReconnectTimer)
      this.socketReconnectTimer = setTimeout(() => {
        console.log('WebSocket:重连中...')
        this.socketReconnectLock = false
        // websocket启动
        this.createWebSocket()
      }, 4000)
    },
    // 连接成功建立的回调
    onOpenCallback: function (event) {
      console.log('WebSocket:已连接')
      // 心跳检测重置
      // this.heartCheck.reset().start();
    },
    // 连接发生错误的回调
    onErrorCallback: function (event) {
      console.log('WebSocket:发生错误')
      // websocket重连
      this.socketReconnect()
    },
    // 连接关闭的回调
    onCloseCallback: function (event) {
      console.log('WebSocket:已关闭')
      // 心跳检测重置
      this.heartCheck.reset()
      if (!this.socketLeaveFlag) {
        // 没有离开——重连
        // websocket重连
        this.socketReconnect()
      }
    },
    // 向后端发送数据的回调
    onSendCallback: function () {
      console.log('WebSocket:发送信息给后端')
    },
    // 接收到消息的回调
    getMessageCallback: function (msg) {
      // console.log(msg.data);
      if (msg.data.indexOf('HeartBeat') > -1) {
        // 心跳回复——心跳检测重置
        // 收到心跳检测回复就说明连接正常
        console.log('收到心跳检测回复')
        // 心跳检测重置
        this.heartCheck.reset().start()
      } else {
        // 普通推送——正常处理
        let data = JSON.parse(msg.data)
        console.log('收到推送消息', data)
        this.bjList = [...data.dataList]
        if (data.yjdsl) {
          this.yjdsl = data.yjdsl
        }
        // this.$nextTick(() => {
        //     that.$refs.leftMiddle.scrollTop = that.$refs.leftMiddle.scrollHeight;
        // });
      }
    }
  }
}
